#pragma once

#include <memory.h>

#include "command.hpp"
#include "components.hpp"

#include "baseCommandReceiver.hpp"

#include "events.hpp"
#include "qbe/src/ecs/event.hpp"

#include <entt/entt.hpp>

#include "qbe/src/layout/layout_cmd.hpp"

namespace qbe::undoRedoT {

// 批量添加时，最后额外新增的命令，专用于调用LayoutCmd.add(std::vector<entt::entity>)
class ChangeObjCRs : public BaseCommandReceiver {
 public:
  ChangeObjCRs();
  ~ChangeObjCRs();

  virtual bool Action(bool bUndo) override;
  void Prepare(entt::registry* _reg, std::vector<entt::entity> _earr, ecs::EventWriter<Event>& _event_writer, layout::LayoutCmd* _cmd);

 private:
  entt::registry* reg = nullptr;
  std::vector<entt::entity> earr;

  ecs::EventWriter<Event>* event_writer;
  layout::LayoutCmd* cmd;

  bool first{true};
  bool redo{false};
  bool undo{false};
};

ChangeObjCRs::ChangeObjCRs() {}

ChangeObjCRs::~ChangeObjCRs() {}

void ChangeObjCRs::Prepare(entt::registry* _reg, std::vector<entt::entity> _earr, ecs::EventWriter<Event>& _event_writer, layout::LayoutCmd* _cmd) {
  reg = _reg;
  earr = _earr;

  event_writer = &_event_writer;
  cmd = _cmd;

  redo = true;
}

bool ChangeObjCRs::Action(bool bUndo) {
  if ((bUndo && !undo) || (!bUndo && !redo))
    return false;

  if (first) {
    first = false;
  } else if (bUndo) {
    cmd->update(earr);
  } else {
    cmd->update(earr);
  }

  undo = !undo;
  redo = !redo;

  return true;
}

}  // namespace qbe::undoRedoT
